// auth.js - 微信授权公共逻辑
class WeChatAuth {
    constructor() {
        this.appId = 'wx0d6fd6596e1e4b49';
        this.isChecking = false;
    }

    // 检查授权状态
    async checkAuth() {
        if (this.isChecking) return;
        this.isChecking = true;

        const openid = localStorage.getItem('wechat_openid');
        
        // 已有openid，直接返回
        if (openid) {
            console.log('检测到本地openid，跳过授权流程');
            this.isChecking = false;
            return true;
        }

        // 非微信环境，跳转首页
        if (!this.isWechatBrowser()) {
            console.log('非微信环境，跳转首页');
            this.redirectToHome();
            return false;
        }

        // 检查URL中是否有授权code
        const code = this.getAuthCode();
        
        if (code) {
            // 有code，获取openid
            try {
                await this.getOpenidByCode(code);
                this.removeAuthCodeFromUrl();
                this.isChecking = false;
                return true;
            } catch (error) {
                console.error('获取openid失败:', error);
                this.redirectToHome();
                return false;
            }
        } else {
            // 没有code，跳转首页
            console.log('未检测到授权code，跳转首页');
            this.redirectToHome();
            return false;
        }
    }

    // 检查是否微信浏览器
    isWechatBrowser() {
        return /MicroMessenger/i.test(navigator.userAgent);
    }
 // 显示提示通知
    showNotification(message) {
        // 创建提示框元素
        const notification = document.createElement('div');
        notification.style.cssText = `
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: rgba(0, 0, 0, 0.8);
            color: white;
            padding: 20px 30px;
            border-radius: 8px;
            font-size: 16px;
            z-index: 9999;
            text-align: center;
            max-width: 80%;
            word-break: break-all;
        `;
        notification.textContent = message;

        // 创建半透明背景遮罩
        const overlay = document.createElement('div');
        overlay.style.cssText = `
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            z-index: 9998;
        `;

        // 添加到页面
        document.body.appendChild(overlay);
        document.body.appendChild(notification);

        // 2秒后自动移除
        setTimeout(() => {
            if (document.body.contains(notification)) {
                document.body.removeChild(notification);
            }
            if (document.body.contains(overlay)) {
                document.body.removeChild(overlay);
            }
        }, 2000);
    }

    // 获取URL中的授权code
    getAuthCode() {
        const urlParams = new URLSearchParams(window.location.search);
        return urlParams.get('code');
    }

    // 跳转到首页
    redirectToHome() {
        // 避免重复跳转
        console.log(window.location.pathname,'pathname');
        
        if (window.location.pathname !== '/login.html' && window.location.pathname !== '/') {

            window.location.href = '/login.html';
        }
        this.isChecking = false;
    }

    // 通过code获取openid（需要后端支持）
    async getOpenidByCode(code) {
        try {
            // 调用后端接口，用code换openid
            const response = await fetch(`/api/wechat/auth?code=${code}`);
            const result = await response.json();
            
            if (result.success && result.data.openid) {
                localStorage.setItem('wechat_openid', result.data.openid);
                // 如果有用户信息也保存
                if (result.data.userInfo) {
                    localStorage.setItem('wechat_userinfo', JSON.stringify(result.data.userInfo));
                }
                console.log('微信授权成功，获取到openid:', result.data.openid);
            } else {
                throw new Error(result.message || '获取openid失败');
            }
        } catch (error) {
            console.error('获取openid失败:', error);
            // 获取openid失败也跳转首页
            this.redirectToHome();
            throw error;
        }
    }

    // 从URL中移除code参数
    removeAuthCodeFromUrl() {
        const url = new URL(window.location.href);
        url.searchParams.delete('code');
        url.searchParams.delete('state');
        window.history.replaceState({}, document.title, url.toString());
    }

    // 获取openid
    getOpenid() {
        return localStorage.getItem('wechat_openid');
    }

    // 获取用户信息
    getUserInfo() {
        const userInfo = localStorage.getItem('wechat_userinfo');
        return userInfo ? JSON.parse(userInfo) : null;
    }

    // 检查是否已授权（基于openid）
    isAuthenticated() {
        return !!this.getOpenid();
    }

    // 退出登录
    logout() {
        localStorage.removeItem('wechat_openid');
        localStorage.removeItem('wechat_userinfo');
        localStorage.removeItem('wechat_token'); // 清理可能存在的旧token
        console.log('已退出登录，清除本地openid');
    }

    // 强制重新授权（清除本地openid并跳转首页）
    forceReauth() {
        this.logout();
        this.redirectToHome();
    }
}

// 创建全局实例
window.weChatAuth = new WeChatAuth();

// 页面加载时自动检查
document.addEventListener('DOMContentLoaded', function() {
    window.weChatAuth.checkAuth();
});